package cn.wen.core.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;

public class APPUtils {

    private APPUtils() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    private static Context mContext;
    private static int mMainId;
    private static Handler mHandler;

    public static void init(Context context) {
        mContext = context;
        mMainId = Process.myTid();
        mHandler = new Handler(Looper.getMainLooper());
    }


    /**
     * 获取Context
     */
    public static Context getContext() {
        return mContext;
    }

    /**
     * 获取Handler
     */
    public static Handler getHandler() {
        return mHandler;
    }


    /**
     * 是否运行在主线程
     */
    public static boolean isRunInMainThread() {
        return Process.myTid() == mMainId;
    }

    /**
     * 在主线程执行一个任务
     *
     * @param runnable
     */
    public static void runInMainThread(Runnable runnable) {
        if (isRunInMainThread()) {
            // 在主线程
            runnable.run();
        } else {
            // 不在主线程
            getHandler().post(runnable);
        }
    }

    /**
     * 获取应用程序名称
     */
    public static String getAppName() {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    mContext.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return mContext.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @return 当前应用的版本名称
     */
    public static String getVersionName() {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    mContext.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取app版本号
     */
    public static int getVersionCode() {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    mContext.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
